import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:ota_update/ota_update.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';

import '../../http/apis.dart';

class VersionUpdate {

  /**
   * 检查更新
   */
  static checkUpdate(BuildContext context) async {

    // 接口获取更新内容
    // var params = {
    //   'templateCode': "audio_video",
    // };
    // HttpUtils.get(APIs.courseList, params, context: context, success: (res) {
    //   String version = packageInfo.version;
    //   // v['data']['version'] 为后端返回的最新版本
    //   var isUpdate = haveNewVersion(res['data']['version'], version);
    //   if (isUpdate) {
    //     // v['data']['path'] 为后端返回的服务器apk路径
    //     _showNewVersionAppDialog(context,"更新内容",res['data']['path'],false);
    //   }
    // }, fail: (code, msg) {
    //   print("error");
    // });


    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //获取当前的版本号
    int currentVersionCode = int.parse(packageInfo.version.replaceAll('.', ''));
    print("ah  currentVersionCode == ${currentVersionCode}");

    int serviceVersionCode = 101;
    String updateMsg ="1.更新内容。\n 2.更新内容22。";
    String downloadUrl = "https://xdo-storage.oss-cn-beijing.aliyuncs.com/soft/xyfapp/app-xueyoufang-release-v1.2.0-120-20221116-140634.apk";
    bool isForce = false;


    //如果获取服务器的版本号比当前应用程序的版本号还高，那么提示升级
    if (serviceVersionCode > currentVersionCode) {
      if (Platform.isAndroid) {
        //Android平台在应用内进行更新
        //弹出"版本更新"的对话框
        UpdateDialog.showUpdateDialog(context, updateMsg,downloadUrl, isForce);
      } else if (Platform.isIOS) {
        //iOS平台跳转道AppStore进行更新
      }
    }
  }



}

class UpdateDialog extends Dialog {
  final String updateContent;
  final String downloadUrl;
  final bool isForce;

  UpdateProgress updateProgressProvider = new UpdateProgress();

  UpdateDialog({this.updateContent = "",this.downloadUrl = "", this.isForce = false});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context)=>updateProgressProvider,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 280,
              height: 300,
              child: Stack(
                children: <Widget>[
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(20))
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(top: 50),
                          child: Text('发现新版本',
                              style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.black54,
                                  decoration: TextDecoration.none)),
                        ),
                        Text(updateContent,
                            style: TextStyle(
                                fontSize: 16,
                                color: Colors.black54,
                                decoration: TextDecoration.none)),

                        Consumer<UpdateProgress>(
                            builder: (ctx, updateProgress, child){
                              return Container(
                                  margin: EdgeInsets.only(left: 10,right: 10),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.all(Radius.circular(10)),
                                    child: LinearProgressIndicator(
                                      valueColor: AlwaysStoppedAnimation(Colors.lightBlueAccent),
                                      minHeight: 10,
                                      backgroundColor: Colors.black12,
                                      value: updateProgress!=null?int.parse(updateProgress.progress!)/100:0.1,
                                    ),
                                  )
                              );
                            }),

                        Container(
                          width: 220,
                          height: 42,
                          margin: EdgeInsets.only(bottom: 15),
                          child: ElevatedButton(
                              child: Text(
                                '立即更新',
                                style:
                                TextStyle(fontSize: 18, color: Colors.white),
                              ),
                              onPressed: () {
                                doUpdate(context,downloadUrl);
                              }),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Navigator.pop(context);
              },
              child: Offstage(
                offstage: isForce,
                child: Container(
                    margin: EdgeInsets.only(top: 30),
                    child: Image.asset(
                      'images/close_audio_list.png',
                      width: 35,
                      height: 35,
                    )),
              ),
            )
          ],
        ),
      ),
    );
  }

  static showUpdateDialog(BuildContext context, String updateContent,String downloadUrl,bool isForce) {
    return showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return WillPopScope(
              child: UpdateDialog(
                  updateContent: updateContent,downloadUrl: downloadUrl , isForce: isForce),
              onWillPop: _onWillPop);
        });
  }

  static Future<bool> _onWillPop() async {
    return false;
  }

  /**
   * 下载apk
   */
  doUpdate(BuildContext context, path) async {
    try {
      // destinationFilename 是对下载的apk进行重命名
      var destinationFilename = path.toString().substring(
          path.toString().lastIndexOf('/') + 1);

      OtaUpdate().execute(
        path,
        destinationFilename: destinationFilename,
      ).listen(
            (OtaEvent event) {
          try {
            switch (event.status) {
              case OtaStatus.DOWNLOADING: // 下载中
                updateProgressProvider.setProgress(event?.value);
                break;
              case OtaStatus.INSTALLING: //安装中=
                break;
              case OtaStatus.PERMISSION_NOT_GRANTED_ERROR: // 权限错误
                break;
              default: // 其他问题
                break;
            }
          } catch (e) {
            print('ah  OtaUpdate === 错误：$e');
          }
        },
      );
    } catch (e) {
      print('ah OtaUpdate  === 更新失败');
    }
  }
}


class UpdateProgress extends ChangeNotifier{
  String? _progress = "0";
  void setProgress(String? p) {
    this._progress = p;
    notifyListeners();
  }
  String? get progress => _progress;
}